/**
 * HTTp 请求工具类
 * @param url
 * @returns {string}
 */
function appendHost(url) {
    return"http://localhost/shop_api/"+url;
}
function appendHost2(url) {
    return"http://localhost/shop-admin/"+url;
}


function convertToFormData(params) {
    var data = new FormData();
    for (var key in params) {
        data.append(key, params[key]);
    }
    return data;
}
/**
 * 请求上传文件
 * @param url
 * @param params
 * @param respCallBack
 */
function httpPostWithFile(url, params, respCallBack) {
    url = appendHost(url);
    var data = convertToFormData(params);
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        cache: false,
        processData: false,
        contentType: false,
        success: function (resp) {
            handleResp(resp, respCallBack);
        }
    });
}

/**
 * 转对象->判断是否请求成功
 * @param resp 返回参数
 * @param callback 回调函数
 */
function handleResp(resp,callback) {
    //把Json对象转化成JS对象
    console.log(resp);
    let result=JSON.parse(resp);
    console.log(result);
    if (result.code == 0){
        callback(result.data);
    }else{
        alert(result.message);//失败
    }
}

function error(XMLHttpRequest,textStatus,errorThrown) {
    alert("失败"+XMLHttpRequest.status+":"+textStatus+":"+errorThrown);
}
/**
 * get 带参请求
 * @param url
 * @param params
 * @param callback
 */
function httpGet(url,params,callback) {
    //url 拼接服务器ip和端口地址
    url = appendHost(url);
    // let paramsJson=JSON.stringify(params);
    $.get(url,params,function (resp) {
        handleResp(resp,callback);
    });
}
function httpPost(url,params,callback) {
    url=appendHost(url);
    let paramsJson=JSON.stringify(params);
    $.ajax({
        type:"POST",
        url:url,
        contentType:"application/json; charset=utf-8",
        data:paramsJson,
        success:function (resp) {
            handleResp(resp,callback);
        }
    });

}


//请求信息
function loadUser2(){
    //ajax 请求后台
    $.ajax({
        url:"http://localhost:8080/myShow-api/user/select",
        method:"post",
        success:function (resp) {
        handleResp(resp,showMsg2());
    },
        error:function(XMLHttpRequest,textStatus,errorThrown){
            alert("失败"+XMLHttpRequest.status+":"+textStatus+":"+errorThrown);
        }
    });
}
//渲染用户信息
function showMsg2(res) {
    console.log("showMsg")
    console.log(res);
    let r=JSON.parse(res);
    var html = res.map(function (s) {
        var template =
            `<tr class="tr_head">
                    <td></td>
                    <td>${s.userId}</td>
                    <td>${s.username}</td>
                    <td>${s.password}</td>
                    <td>${s.address}</td>
                    <td>${s.phone}</td>
                    <td><button class="btn btn-warning" onclick="delUser(${s.userId})">删除</button></td>
                    </tr>`;
        return template
    }).join("");
    $("#tb_list").html(html);
}
